//
//  GameViewController.m
//  FirstGame
//
//  Created by iD Student on 7/8/13.
//  Copyright (c) 2013 jasonkurtzman. All rights reserved.
//

#import "GameViewController.h"
#import "Enemy.h"

@interface GameViewController ()

@end

@implementation GameViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) loadGame
{
    timeRemaining = 30;
    score = 0;
    if(enemyList == nil)
        enemyList = [[NSMutableArray alloc] initWithCapacity:0];
    else
        [enemyList removeAllObjects];
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:.25 target:self selector:@selector(gameUpdate) userInfo:nil repeats:YES];
    scoreLabel.text = @"Score: 0";
}

-(void) gameUpdate
{
    if(timeRemaining <= 0)
    {
        [self gameOver];
    }
    timeRemaining -= .25;
    if(timeRemaining % 2 == 0)
    {
        //Spawn New Enemy
        Enemy *enemy = [[Enemy alloc] init];
        enemy.imageView.center = CGPointMake(arc4random() % 280 + 20, arc4random() % 400 + 20);
        [enemyList addObject:enemy];
        [self.view addSubview:enemy.imageView];
        
        int count = self.view.subviews.count;
        count = count;
    }
    
    int i = 0;
    while(i < [enemyList count])
    {
        Enemy *enemy = [enemyList objectAtIndex:i];
        if(enemy.alive == NO)
        {
            [enemy.imageView removeFromSuperview];
            [enemyList removeObject:enemy];
        }else
            i++;
    }
}

-(void) gameOver
{
    [gameTimer invalidate];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over" message:[NSString stringWithFormat:@"You Scored: %d", score] delegate:self cancelButtonTitle:@"Main Menu" otherButtonTitles:nil, nil];
    [alert show];
    //[alert release];
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    for(Enemy *enemy in enemyList)
    {
        if(CGRectContainsPoint(enemy.imageView.frame, touchPoint))
        {
            if(enemy.alive == YES)
            {
                enemy.alive = NO;
                score += enemy.pointValue;
                scoreLabel.text = [NSString stringWithFormat:@"Score: %d", score];
                break;
            }
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
